package com.hvgroup.modules.sanic.service.impl;

import com.hvgroup.modules.sanic.domain.dto.KnowledgeBase;
import com.hvgroup.modules.sanic.domain.dto.KnowledgeBaseItem;
import com.hvgroup.modules.sanic.service.DifyKBService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DifyKBServiceImpl implements DifyKBService {

    @Value("${dify.api.key.app}")
    private String difyApiKeyApp;

    @Value("${dify.api.key.dataset}")
    private String difyApiKeyDs;

    @Value("${dify.api.url.root}")
    private String difyApiUrl;

    /**
     * 创建知识库
     */
    @Override
    public String createDatasets(KnowledgeBase request) {
        return WebClient.builder().baseUrl(difyApiUrl).build().post()
                .uri("/v1/datasets")
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(request)
                .retrieve()
                .bodyToMono(KnowledgeBase.class)
                .map(KnowledgeBase::getId)
                .block();
    }

    /**
     * 获取知识库列表
     */
    @Override
    public List<KnowledgeBaseItem> listDatasets(String page) {
        return WebClient.builder().baseUrl(difyApiUrl).build().get()
                .uri("/v1/datasets?limit=20&page=" + page)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里
                .retrieve()
                .bodyToFlux(KnowledgeBaseItem.class)
                .collectList()
                .block();
    }

    @Override
    public List<KnowledgeBaseItem> listDatasetsItem(String datasetId) {
        return WebClient.builder().baseUrl(difyApiUrl).build().get()
                .uri(String.format("/v1/datasets/%s/documents", datasetId))
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里
                .retrieve()
                .bodyToFlux(KnowledgeBaseItem.class)
                .collectList()
                .block();
    }


    /**
     * 向指定知识库上传文件
     */
    @Override
    public void uploadFileToDatasets(String datasetId, MultipartFile file) {
        try {
            WebClient.builder().baseUrl(difyApiUrl).build().post()
                    .uri(String.format("/datasets/%s/document/create-by-file", datasetId))
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里
                    .contentType(MediaType.MULTIPART_FORM_DATA)
                    .body(BodyInserters.fromMultipartData("file", new FileSystemResource(file.getResource().getFile()))
                            .with("knowledge_base_id", datasetId))
                    .retrieve()
                    .bodyToMono(Void.class)
                    .block();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 更新指定知识库信息
     */
    @Override
    public void updateKnowledgeBase(String datasetId, KnowledgeBaseItem request) {
        String documentId = "2", text = "1";
        WebClient.builder().baseUrl(difyApiUrl).build().post()
                .uri(String.format("/datasets/%s/documents/%s/update-by-text", datasetId, documentId))
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .retrieve()
                .bodyToMono(Void.class)
                .block();
    }

    /**
     * 删除知识库
     */
    @Override
    public void deleteDatasets(String dsId) {
        WebClient.builder().baseUrl(difyApiUrl).build().delete()
                .uri("/v1/datasets/" + dsId)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里// 请求 S
                .retrieve()
                .bodyToMono(Void.class)
                .block();
    }

    /**
     * 文档
     */
    @Override
    public void deleteDatasetsItem(String datasetId, String documentId) {
        WebClient.builder().baseUrl(difyApiUrl).build().delete()
                .uri(String.format("/datasets/%s/documents/%s", datasetId, documentId))
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKeyDs)         // Bearer token 前缀已包含在 authToken里// 请求 S
                .retrieve()
                .bodyToMono(Void.class)
                .block();
    }

}
